"use client"
import $ from 'jquery';
import 'orgchart/dist/css/jquery.orgchart.min.css'; // 引入 OrgChart 的 CSS
import 'orgchart/dist/js/jquery.orgchart.js'; // 引入 OrgChart 的 JS
import { useEffect, useRef } from 'react';
import { data } from './data';
import './styles.scss';
// 主要内容
const OrgChartComponent = () => {
  const orgChartRef = useRef(null);

  useEffect(() => {
    if (!orgChartRef.current) return;
    if (!window || !(typeof window !== 'undefined')) return;
    // 初始化组织结构图
    let nodeTemplate = function (data: any) {
      console.log('====67', data);
      // const length = data.label.length * 16
      let name = data.label;
      let isBtn = data.children?.length > 0 && data.level === 5;
      // 没有名字的显示竖线
      if (!name) {
        return `<div class='itemBoxLine' style="
        width:1.5px;
        height:35px;
        background:#e3e5e4;
        transform: scaleY(1.1)
      ">
        </div>`
      }
      // 竖着
      if (data.level === 6) {
        name = data.label
          .split('')
          .map((i) => `${i}</br>`)
          .join('');
        return `<div class='itemBox' style="width:70px">
          <div class='itemText' style="width:30px">${name}</div>
        </div>`;
      }
      // 添加收起
      return `<div class='itemBox'>
          <div class='itemText'>${name}</div>
           <div class='${isBtn ? 'itemBtn' : 'noBtn'}' id='${data.id}'> 
      <svg t="1728961432122" class="icon" viewBox="0 0 1024 1024" version="1.1"  p-id="4040" width="15" height="15"><path d="M64 512A448 448 0 1 0 512 64 448 448 0 0 0 64 512z m497.28-210.24a729.6 729.6 0 0 1 224 224 96 96 0 1 1-164.48 98.88 496 496 0 0 0-108.8-122.56 564.8 564.8 0 0 0-109.12 123.52 96 96 0 1 1-164.48-98.88 729.6 729.6 0 0 1 224-224 96 96 0 0 1 98.88-0.96z" fill="#1bcae1" p-id="4041"></path></svg>
           <div>
      </div>`;
    };
    const orgChart = $(orgChartRef.current).orgchart({
      data: data,
      nodeTemplate: nodeTemplate,
      pan: true,
      zoom: true,
      // zoominLimit: 3,
      toggleSiblingsResp: false,
      parentNodeSymbol: null,

      createNode: function ($node, data) {
        if (data.level > 2) {
          // $node.find('.itemBtn')
        }
      },
      // 绑定点击事件
      // 其他选项可以在这里设置
    });
    // 收起 展开
    $(orgChartRef.current).on('click', '.itemBtn', function () {
      const nodeId = '#' + $(this)[0].id;
      console.log('===890', orgChart, nodeId, $(nodeId));
      let flag = orgChart.getNodeState($(nodeId), 'children').visible;
      if (flag) {
        orgChart.hideChildren($(nodeId));
      } else {
        orgChart.showChildren($(nodeId));
      }
    });
    $(orgChartRef.current).addClass('noncollapsable');
    // 清理函数，以防止内存泄漏
    return () => {
      $(orgChartRef.current)?.empty(); // 清空 DOM
    };
  }, []);

  return <div ref={orgChartRef}></div>;
};

export default OrgChartComponent;
